<template>
  <el-form label-position="top" class="task-flow-setting">
    <!--S 预览组件 -->
    <div v-if="showFormBuilder" class="flow-setting-left flex-direction-column">
      <div class="flow-preview-header">{{$t('common.base.preview1')}} <base-language-dropdown class="flow-preview-header-translate" v-if="showSetLanguage" :options="languagesList" :lang="formPreviewLocale" @change="changeLocale" /></div>
      <form-preview :fields="fields" class="flow-setting-form-preview  task-form-preview-container">
        <div class="flow-preview-guide" v-if="fields.length == 0">
          <img src="@src/assets/img/task/form-guide.png"/>
          <p class="form-no-tip"> {{ $t('task.setting.taskTypeSetting.flow.formNullTip1')}}</p>
        </div>
        <div class="guide-tip"  v-if="fields.length == 0">
          <p>{{ $t('task.setting.taskTypeSetting.flow.formNullTip2')}}</p>
          <i class="iconfont icon-quxianjiantou"></i>
        </div>

        <div class="form-preview-box">
          <el-button
           type="primary"
            class="form-preview-btn"
            key="isNewButton"
            @click="beforeOpenFormRemind"
            :disabled="isCommonEditState"
            v-if="TASK_NODE_MODE.includes(type) && isHaveNodeFlowAuth"
          >
            {{ $t('common.task.formFieldSet') }}
          </el-button>
          <el-button
            v-else
            type="primary"
            class="form-preview-btn"
            @click="openFormDesign"
          >
            {{ type === "create" ? $t('event.setting.serviceEventTypeSetting.flow.component.settingFlowPreview.btn1') : $t('event.setting.serviceEventTypeSetting.flow.component.settingFlowPreview.btn2') }}
          </el-button>
        </div>
      </form-preview>
    </div>
    <!--E 预览组件 -->

    <!--S 预览问卷组件 -->
    <div v-if="showQuestion" class="flow-setting-left">
      <div class="form-design-main">
          <div class="form-design-center" style="min-height: 420px">
              <div class='form-design-phone'>
                <div style="height:100%;">
                  <iframe id="iframepage" ref="iframePage" :src="this.iframeUrl" height="92%" width="100%"/>
                </div>
              </div>
              <div class="form-preview-box">
                <el-button
                  type="primary"
                  class="form-preview-btn"
                   @click="openSetReviewQuestion"
                >
                  {{$t('task.setting.taskTypeSetting.flow.components.reviewSetting')}}
                </el-button>
              </div>
          </div>
      </div>
    </div>
    <!--E 预览问卷组件 -->

    <!--S 设置项 -->
    <process-node-setting
      v-if="type=='normal'"
      :key="compKey"
      :curFlowName="curFlowName"
      :triggerGray="triggerGray"
      :showApproveSetting="showApproveSetting"
      :taskTypeId="taskTypeId"
      :type="type"
      :flowSetting="flowSetting"
      :isUpdate="isUpdate"
      :taskOverTimeModel="taskOverTimeModel"
      :preFlowName="preFlowName"
      :options="options"
      :optionMaps="optionMaps"
      :flag="flag"
      :overTimeOptions="overTimeOptions"
      :currentNode="currentNode"
      :isNewNormalNode="isNewNormalNode"
      :taskTypeName="taskTypeName"
      :flowCardList="flowCardList"
      :flowProcessList="flowProcessList"
      :isEdit="isEditState"
      @changeApproveSetting="changeApproveSetting"
      @handleChooseUserSubmit="handleChooseUserSubmit"
      @openFormDesign="beforeOpenFormRemind"
      @flowCardChange="(e) => $emit('flowCardChange', e)"
      >
    </process-node-setting>
    <div class="flow-setting-right" :key="compKey" v-else>
      <el-tabs 
        class="el-tabs-wrap el-tabs-setting" 
        v-model="baseSetActiveTab"   
        :key="`${type}_${questionId}`" 
        v-if="isShowBaseTabSetting">
        <el-tab-pane :label="$t('portal.setting.title1')" name="base"></el-tab-pane>
        <el-tab-pane :label="$t('event.setting.constant.setting_step.name2')" name="senior"></el-tab-pane>
      </el-tabs>
      <div class="setting-specific">
        <!--S 工单表单设置 -->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <div v-if="showFormBuilder" class="setting-specific-form">
          <h2 class="mt-12">{{$t('task.setting.taskTypeSetting.flow.components.taskFormSetting')}}</h2>
          <el-button type="text" @click="beforeOpenFormRemind">
            <template v-if="type === 'create'">{{$t('task.setting.taskTypeSetting.flow.components.taskCreateFormSetting')}}</template>
            <template v-else-if="type === 'finish'">{{$t('task.setting.taskTypeSetting.flow.components.taskReceiptFormSetting')}}</template>
            <template v-else>{{$t('task.setting.taskTypeSetting.flow.components.taskNewNodeSetting')}}</template>
          </el-button>
        </div>
        </div>
        <!--E 工单表单设置 -->

        <!--S 回访问卷方案设置-->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <div v-if="type === 'review' && customerSatisfaction" class="mt-8">
          <h2 class="mt-12">{{$t('task.setting.taskTypeSetting.flow.components.reviewQuestionSetting')}}</h2>
          {{$t('task.setting.taskTypeSetting.flow.components.selectExistingScheme')}}           
          <el-select
              v-model="flowSetting.questionId"
              @change="changeQuestion"
            >
              <el-option
                v-for="item in usedConfigList"
                :key="item.satisfactionId"
                :label="item.satisfactionName"
                :value="item.satisfactionId"
              >
              </el-option>
            </el-select>
          <p class="set-review-question" @click="openSetReviewQuestion">
            {{$t('task.setting.taskTypeSetting.flow.components.goToSetReviewScheme')}}
          </p>
        </div>
        </div>
        <!--E 回访问卷方案设置-->
        <!--S 审批设置 -->
        <div v-show="!isHaveNodeFlowAuth || ['cost', 'close'].includes(type)  || baseSetActiveTab == 'base'">
        <div
          v-if="showApproveSetting"
          :class="['setting-specific-approve']"
        >
          <h2>
            {{ type === "allot" ? $t('task.setting.taskTypeSetting.flow.components.title2') : $t('task.setting.taskTypeSetting.flow.components.title1') }}
          </h2>
          <!-- {{type}} -->
          <!-- {{flowSetting.approveSetting}} -->
          <approve-setting
            :flowType="type"
            :options="options.flow"
            :isUpdate="isUpdate"
            :optionMaps="optionMaps"
            :task-type-id="taskTypeId" 
            :approve-setting="flowSetting.approveSetting"
            :currentNodeId="currentNode.id"
            @change="(setting) => changeApproveSetting(setting, 'assign')"
          />
        </div>
        <!--E 审批设置 -->

        <!--S 转派时也审批-->
        <!-- <div v-if="type === 'allot' && (flowSetting.approveSetting.level && flowSetting.approveSetting.level > 0)" class="mt-8">
          <el-checkbox v-model="flowSetting.reallotAppr" true-label="" false-label="none"
          >转派时也审批</el-checkbox
          >
        </div> -->
        <!--E 转派时也审批-->

        <!-- S 允许审批人修改回执表单 -->
        <div v-if="type == 'finish'">
          <el-checkbox v-model="flowSetting.approveEditReceipt">
          {{$t('task.setting.taskTypeSetting.flow.components.title3')}}</el-checkbox>
        </div>
      </div>
          
        <!-- E 允许审批人修改回执表单 -->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'senior'">
        <div v-if="type == 'finish' && haveFaceCheckGray">
          <h2>{{ $t('task.face.setting.tips3') }}<el-switch class="mar-l-16" v-model="flowSetting.finishByFaceId"></el-switch></h2>
          <div>{{ $t('task.face.setting.tips4') }}</div>
        </div>
        <div v-if="type == 'finish' && haveOnlinePayGray">
          <h2>{{ $t('task.detail.components.onlinePay') }}<el-switch class="mar-l-16" v-model="flowSetting.finishOnlinePay"  @change="onChangeOnlinePay"></el-switch></h2>
          <div>{{ $t('task.paySet.tip1') }}</div>
        </div>
        </div>

        <!-- 转派审批设置start -->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <div
          v-if="['allot'].includes(type)"
          :class="['setting-specific-approve',showFormBuilder && 'mt-12']"
        >
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.title4')}}
          </h2>
          <approve-setting
            :flowType="type"
            flowTypeStr="reAllot"
            :options="options.flow"
            :isUpdate="isUpdate"
            :optionMaps="optionMaps"
            :task-type-id="taskTypeId" 
            :approve-setting="flowSetting.transferApprove"
            @change="(setting) => changeApproveSetting(setting, 'reassign')"
          > 
            <template slot='reassign'>
              <el-radio :label="3" class="ml-12">{{$t('task.setting.taskTypeSetting.flow.components.title5')}}</el-radio>
            </template>
          
          </approve-setting>
            
        </div>
      </div>
        <!-- 转派审批设置end -->
      <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <!--S 自动回访 -->
        <div v-if="showReview" class="setting-specific-auto-review">
          <h2>
            {{$t('task.taskTypes.review.autoReview')}}
            <el-switch v-model="taskTypeConfig.autoReviewState" />
          </h2>
          <p>
            {{$t('task.setting.taskTypeSetting.flow.components.tip2')}}
          </p>
        </div>
      </div>
        <!--E 自动回访 -->

        <!--S 超时提醒 -->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <div v-if="showOvertime" class="setting-specific-overtime">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.title6')}}
            <!-- ps: 不希望切换流程节点时，switch有动画 -->
            <el-switch
              v-show="taskOverTimeModel.overTimeStatus && !flag"
              class="ml-12"
              :value="true"
              @change="(val) => {
                $set(taskOverTimeModel,'overTimeStatus', false);
                updateOvertimeSetting()
              }"
            />
            <el-switch
              v-show="!taskOverTimeModel.overTimeStatus && !flag"
              class="ml-12"
              :value="false"
              @change="() => {
                $set(taskOverTimeModel,'overTimeStatus', true);
                updateOvertimeSetting()
              }"
            />
            <el-switch
              v-show="flag"
              class="ml-12"
              v-model="taskOverTimeModel.overTimeStatus"
              @change="updateOvertimeSetting"
            />
          </h2>
          <div class="lh-38" v-show="taskOverTimeModel.overTimeStatus">
            {{ preFlowName }}
            <i18n path="task.setting.taskTypeSetting.flow.components.title7">
              <el-input
                place="num"
                class="w-87"
                onkeyup="if(isNaN(value))execCommand('undo')"
                maxlength="4"
                v-model="flowSetting.overTime"
              />
            </i18n>
          </div>
          <div class="lh-38" v-show="taskOverTimeModel.overTimeStatus">
            {{$t('task.setting.taskTypeSetting.flow.components.title8')}}
            <el-select
              v-model="taskOverTimeModel.remindType"
              @change="updateOvertimeSetting"
            >
              <el-option
                v-for="item in overTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            
            <template>
              <el-input
                v-if="taskOverTimeModel.remindType === null && !isOpenData"
                class="w-187"
                :placeholder="$t('task.setting.taskTypeSetting.flow.components.placeholder1')"
                readonly
                :value="getApproverNames(taskOverTimeModel.reminders)"
                @click.native="selectApproveUser('overTime')"
                @change="updateOvertimeSetting"
              />
              
              <div class="ui-input-block" @click="selectApproveUser('overTime')" v-if="taskOverTimeModel.remindType === null && isOpenData">
                <span class="placeholder-text" v-if="taskOverTimeModel.reminders.length <= 0">
                  {{$t('task.setting.taskTypeSetting.flow.components.placeholder1')}}
                </span>
                <div>
                  <template v-for="(item, index) in taskOverTimeModel.reminders">
                    <open-data :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                    <ui-separator :index="index" :list="taskOverTimeModel.reminders" :key="`${item.staffId}${uuid()}`" />
                  </template>
                </div>
              </div>
              
            </template>
            
            <i18n path="task.setting.taskTypeSetting.flow.components.title9">
              <el-select
                place="num"
                class="w-87"
                v-model="taskOverTimeModel.isAhead"
                @change="updateOvertimeSetting"
              >
                <el-option :label="$t('common.base.before')" :value="1"> </el-option>
                <el-option :label="$t('common.base.after')" :value="0"> </el-option>
              </el-select>
            </i18n>
            <i18n path="task.setting.taskTypeSetting.flow.components.title10">
              <el-input
                place="num"
                class="w-87"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                v-model="taskOverTimeModel.minutes"
                @change="updateOvertimeSetting"
              >
            </el-input>
            </i18n>
          </div>
        </div>
      </div>
        <!--E 超时提醒 -->


        <!--S 回访提醒 -->
        <!-- <div v-if="showReview" class="setting-specific-msg-delay">
          <h2>
            超时提醒
            <el-switch    
              class="ml-12"
              v-model="taskOverTimeModel.overTimeStatus"
              @change="updateOvertimeSetting"
            />
          </h2>
          <div>
            对未回访的工单，在完成工单后的
            <el-input
              class="w-87"
              onkeyup="this.value=this.value.replace(/\D/g,'')"
              v-model="taskOverTimeModel.minutes"
            ></el-input>
            小时后，发送回访提醒至
            <el-select
              v-model="taskOverTimeModel.remindType"
              @change="updateOvertimeSetting"
            >
              <el-option
                v-for="item in overTimeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            
            <template>
              <el-input
                v-if="taskOverTimeModel.remindType === null && !isOpenData"
                class="w-187"
                placeholder="请选择通知人"
                readonly
                :value="getApproverNames(taskOverTimeModel.reminders)"
                @click.native="selectApproveUser('overTime')"
                @change="updateOvertimeSetting"
              />
              
              <div class="ui-input-block" @click="selectApproveUser('overTime')" v-if="taskOverTimeModel.remindType === null && isOpenData">
                <span class="placeholder-text" v-if="taskOverTimeModel.reminders.length <= 0">
                  请选择通知人
                </span>
                <div>
                  <template v-for="(item, index) in taskOverTimeModel.reminders">
                    <open-data :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                    <ui-separator :index="index" :list="taskOverTimeModel.reminders" :key="`${item.staffId}${uuid()}`" />
                  </template>
                </div>
              </div>
 
            </template>
          </div>
        </div> -->
        <!--E 回访提醒 -->
      <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <!--S 自动回访短信延迟发送设置 -->
        <div v-if="showReview" class="setting-specific-msg-delay">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.title11')}}
            <el-switch v-model="taskTypeConfig.delayBack" />
          </h2>
          <div v-show="taskTypeConfig.delayBack">
            <i18n path="task.setting.taskTypeSetting.flow.components.title12">
              <el-input
                place="num"
                class="w-87"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                v-model="taskTypeConfig.delayBackMin"
              ></el-input>
            </i18n>
          </div>
        </div>
      </div>
        <!--E 自动回访短信延迟发送设置 -->

        <!--S 客户回复短信后更新回访状态 -->
      <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'base'">
        <div v-if="showReview" class="setting-specific-msg-delay">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.updateReplyStatus')}}
            <el-switch v-model="taskTypeConfig.reviewWithEvaluate" />
          </h2>
          <div>
            {{$t('task.setting.taskTypeSetting.flow.components.updateReplyStatusTip')}}
          </div>
        </div>
      </div>
        <!--E 客户回复短信后更新回访状态 -->
        <div v-show="!isHaveNodeFlowAuth || baseSetActiveTab == 'senior'">

        <!-- S 是否开启开始工单前出发打卡 -->
        <div v-if="type == 'start'" class="setting-specific-msg-delay">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.taskClockIn')}}
            <el-switch v-model="flowSetting.setOut" class="ml-12" />
          </h2>
          <div>
            {{$t('task.setting.taskTypeSetting.flow.components.taskClockInTip')}}
          </div>
        </div>
        <!-- E 是否开启开始工单前出发打卡 -->

        <div v-if="type == 'start' && haveFaceCheckGray" class="setting-specific-msg-delay">
          <h2>
            {{$t('task.face.setting.tips1')}}
            <el-switch v-model="flowSetting.startByFaceId" class="ml-12" />
          </h2>
          <div>
            {{$t('task.face.setting.tips2')}}
          </div>
        </div>
      </div>

        <!--S 工单自动关闭 -->
        <div v-if="showTaskClose" class="setting-specific-task-close">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.title13')}}
            <el-switch v-model="flowSetting.autoClose" />
          </h2>
          <p>{{$t('task.setting.taskTypeSetting.flow.components.title14')}}</p>
        </div>
        <!--E 工单自动关闭 -->

        <!--S 关闭工单查看权限 -->
        <div v-if="showTaskClose" class="setting-specific-task-view-auth">
          <h2>
            {{$t('task.setting.taskTypeSetting.flow.components.title15')}}
            <el-switch v-model="flowSetting.closeView" />
          </h2>
          <div>
            {{$t('task.setting.taskTypeSetting.flow.components.title16')}}
            <el-select v-model="flowSetting.closeNoViewAuth"></el-select>
            <el-button type="text">{{$t('common.base.view')}}</el-button>
          </div>
        </div>
        <!--E 关闭工单查看权限 -->
      
      <div v-show="!isHaveNodeFlowAuth || ['cost', 'close'].includes(type) || baseSetActiveTab == 'senior'">
        <!--S 触发器 -->
        <trigger-list-setting 
          v-if="triggerGray"
          style="margin-top:12px;"
          :subTitle="$t('common.connector.trigger.subTitle', {curFlowName})" 
          bizType="TASK"
          :bizTypeId="taskTypeId" 
          :bizActionCode="this.type"
        >
        </trigger-list-setting>
        <!--E 触发器 -->

        <!-- S 附加组件 -->
        <card-list-setting 
          v-if="isShowCardListSetting"
          style="margin-top:12px;"
          :subTitle="$t('common.connector.trigger.subTitle', {curFlowName})" 
          bizType="TASK"
          :bizTypeId="taskTypeId" 
          :bizActionCode="this.type"
          :flowCardList="flowCardList"
          :taskTypeName="taskTypeName"
          @flowCardChange="(e) => $emit('flowCardChange', e)"
        >
        </card-list-setting>
        <!-- E 附加组件 -->
      </div>
        
      </div>
    </div>
    <!--E 设置项 -->

    <!-- 表单设置弹窗 -->
    <task-fields-setting
      ref="taskFormSetting"
      :mode="mode"
      :template-id="taskTypeId"
      :template-name="taskTypeName"
      :currentNode="currentNode"
      @success="refreshFields"
    ></task-fields-setting>
      <base-modal :title="title" :show.sync="showGuideDialog" @closed="reset">
        <div class='task-review-list-dialog-body'>
          <div class='task-review-list-dialog-body-text'>
          {{guideMessage.COPY_TEXT_CONTENT}}
          </div>
          <div class='task-review-list-dialog-body-text'>
          {{guideMessage.COPY_TEXT_MESSAGE}}
          <span @click="copyText">{{$t('common.base.copy')}}</span>
          </div>
          <div class='task-review-list-dialog-body-text-min'>
          {{$t('task.setting.taskTypeSetting.flow.components.title17')}}
          </div>
          <div class='task-review-list-dialog-body-btn-group'>
            <el-button class='upgrade-button' type='primary' @click="toSetMessage()">
              {{$t('task.taskTypes.review.goSetSmsTemplate')}}
            </el-button>
          </div>
        </div>
      </base-modal>
  </el-form>
</template>

<script>
import { useLocaleProvide } from '@hooks/useLocale'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
const { isOpenMultiLanguage, languagesList } = useFormMultiLanguage()
// api
import * as TaskApi from '@src/api/TaskApi.ts';
import * as SettingApi from '@src/api/SettingApi.ts';
import * as PayApiApi from '@src/api/PayApi';
// model
import TaskConfig from '@model/types/setting/task/TaskConfig';
import TaskOverTimeSetting from '@model/types/setting/task/TaskOverTimeSetting';
// components
import ApproveSetting from './ApproveSetting.vue';
import TaskFieldsSetting from '@src/modules/setting/task/taskFieldsSetting/TaskFieldsSetting.vue';
import TriggerListSetting from '@src/modules/connector/components/trigger-list-setting/index.vue'
import CardListSetting from '@src/modules/setting/task/taskTypeSetting/flow/components/CardListSetting/CardListSetting.vue';
import ProcessNodeSetting from '@src/modules/setting/task/taskTypeSetting/flow/components/ProcessNodeSetting.vue'
/* enum */
import TableNameEnum from '@model/enum/TableNameEnum.ts';

import flowMap from '../flowMap';
import { getRootWindow } from '@src/util/dom'

import { getRootWindowInitData } from '@src/util/window'
const rootWindowInitData = getRootWindowInitData()
import * as GuideMessage from '@src/model/const/Alert.ts'
import { storageGet, storageSet } from '@src/util/storage';
import { setClipboardData } from '@src/util/dom';
import Platform from '@src/platform'
import { safeNewDate } from '@src/util/time';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import i18n from '@src/locales'
import { haveFaceCheckGray } from '@src/util/grayInfo'
const TASK_NODE_MODE = ['start', 'accept', 'normal'];

export default {
  name: 'flow-setting',
  props: {
    taskTypeId: {
      type: String,
      default: '',
    },
    type: {
      type: String,
      default: 'create',
    },
    flowSetting: {
      type: Object,
      default: () => ({}),
    },
    taskTypeConfig: {
      type: Object,
      default: () => new TaskConfig(),
    },
    isUpdate: {
      type: Boolean,
      default: false,
    },

    flowCardList: {
      type: Array,
      default: () => ([]),
    },
    currentNode: {
      type: Object,
      default: () => ({}),
    },
    flowProcessList: {
      type: Array,
      default: () => ([]),
    },
    isEditState: {
      type: Boolean,
      default: false,
    },
    isNewNormalNode: {
      type: Boolean,
      default: false,
    },
  },
  setup(){
    const { locale: formPreviewLocale, changeLocale } = useLocaleProvide('formPreviewLocale');

    return {
      formPreviewLocale,
      changeLocale,
      languagesList,
    };
  },
  data() {
    return {
      flag: false,
      compKey: safeNewDate().getTime(),
      taskTypeName: '', // 接口返回的工单类型名称

      // 初始化工单/工单回执/回执金额的数据
      optionMaps: {
        task: [],
        task_receipt: [],
        task_receipt_amount: []
      },
      filterTypeList: ['text', 'textarea', 'number', 'select', 'user', 'date', 'phone', 'email', 'formula'],
      fields: [],
      usedConfigList: [],
      flowMap,

      options: {
        pause: [],
        cancel: [],
        flow: []
      },

      overTimeOptions: [
        {
          value: 0,
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label1'),
        },
        {
          value: 1,
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label2'),
        },
        {
          value: null,
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label3'),
        },
      ],

      planOptions: [
        {
          value: '0',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label1'),
        },
        {
          value: '1',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label2'),
        },
        {
          value: '2',
          label: i18n.t('event.setting.constant.over_time_remind_type_options.label3'),
        },
      ],

      taskOverTimeModel: new TaskOverTimeSetting(),

      formList: [], // 表单人员
      receiptList: [], // 回执表单人员,
      questionId: '',
      title: i18n.t('task.taskTypes.review.setGuide'),
      showGuideDialog: false,
      satisfactionTips: "FLOW_SATISFACTION_TIPS",
      iframeUrl:'',
      isOnlineAlipay: false,//是否开启在线支付
      baseSetActiveTab: 'base',
      TASK_NODE_MODE,
    };
  },
  computed: {
    isShowCardListSetting() {
      return !(['review', 'close'].includes(this.type));
    },
    // 展示审批设置
    showApproveSetting() {
      const RootWindow = getRootWindow(window)
      // 开启工单草稿灰度时，新建节点显示审批设置
      if (RootWindow.grayAuth?.taskCreateHalf) return !['accept'].includes(this.type)
      return !['create', 'accept'].includes(this.type)
    },
    guideMessage() {
      return GuideMessage
    },
    customerSatisfaction() {
      // 展示回访问卷方案设置
      return rootWindowInitData?.customerSatisfaction
    },
    showQuestion() { //展示满意度问卷方案
      return  ['review'].includes(this.type) && this.flowSetting.questionId && this.customerSatisfaction;
    },
    showFormBuilder() {
      // 展示表单组件
      const isHaveNode = ['create', 'finish', ...(this.isHaveNodeFlowAuth ? TASK_NODE_MODE : [])];
      return isHaveNode.includes(this.type);
    },
    showApporeve() {
      // 展示审批
      return true;
    },
    showOvertime() {
      // 展示超时提醒
      return !['create', 'cost', 'close'].includes(this.type);
    },
    showReview() {
      // 展示自动回访
      return ['review'].includes(this.type);
    },
    showTaskClose() {
      // 展示工单关闭 (mark_zr: 暂时不做)
      return false && ['close'].includes(this.type);
    },
    showSetLanguage(){
      const isShowLanguage =  ['create', 'finish', ...(this.isHaveNodeFlowAuth ? TASK_NODE_MODE : [])].includes(this.type);
      return isOpenMultiLanguage && isShowLanguage
    },
    mode() {
      if(this.type == 'finish') return TableNameEnum.TaskReceipt
      if(this.type == 'create') return TableNameEnum.Task;

      return this.currentNode.id;

    },
    lastNode() {
      let node = {}
      const currentIndex = this.flowProcessList?.findIndex(item => item.id === this.currentNode?.id)
      if(currentIndex>0) {
        node = this.flowProcessList?.[currentIndex - 1] ?? {}
      }
      return node
    },
    preFlowName() {
      // 上一个启用流程的节点
      let name = '';

      // 判断上一个节点是否是自定义或者当前节点是否自定义，如果是自定义，需要取自定义的title
      if(this.lastNode?.type === 'normal' || this.currentNode?.type === 'normal') {
        return this.lastNode?.title ?? '';
      }

      if(this.type === 'start') {
        return i18n.t('task.setting.taskTypeSetting.flow.flowMap.accept.name');
      }
      for (const key in this.flowMap) {
        if(this.taskTypeConfig.flowSetting[key].state || this.type === key) {
          if(this.type !== 'create' && this.type === key) {
            return name;
          }
          
          name = this.flowMap[key].name;
        }
      }
    },
    curFlowName() {
      // 当前流程的节点
      let name = '';
      return this.flowMap[this.type]?.name || ''
    },
    triggerGray(){
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.TRIGGER || false;
    },
    // 人脸验证灰度
    haveFaceCheckGray(){
      return haveFaceCheckGray();
    },
    /** 在线支付灰度 */
    haveOnlinePayGray(){
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.ONLINE_PAY ?? false;
    },
    newTriggerGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.NEW_TRIGGER || false;
    },
    /**是否是公共节点状态 */
    isCommonEditState() {
      return this.currentNode?.isCommon == 1 && !this.isEditState
    },
    /** 是否开启新工单流程权限 */
    isHaveNodeFlowAuth() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.taskFlowExtend ?? false;
    },
    /** 是否显示基础和高级设置tab（结算和关闭不加tab）*/
    isShowBaseTabSetting() {
      return !(['cost', 'close'].includes(this.type)) && this.isHaveNodeFlowAuth;
    },
  },
  watch: {
    type(val) {
      if (val && val !=='normal') {
        this.flag = false;
        if( !['start', 'accept'].includes(val)){
          this.getTaskFields(val);
        }
        // 获取当前流程超时提醒设置
        this.taskOverTimeModel = this.taskTypeConfig.taskOverTimeModels.find(
          (item) => item.overTimeState === val
        ) || (val==='review' && (Object.assign(new TaskOverTimeSetting(), {overTimeState: 'review'}))) ||{};
        this.options.flow = this.approveOptions(this.type);
        setTimeout(() => {this.flag = true;})

        if(!storageGet(this.satisfactionTips) && this.type === 'review') {
          storageSet(this.satisfactionTips, '1')
          this.showGuideDialog = true;
        }
      }

      // 获取表单 并设置字段默认值
      if( !TASK_NODE_MODE.includes(val)){
        this.initData()
      }
    },
    isUpdate: {
      immediate: true,
      handler(newValue, _) {
        if (newValue) {
          this.initData()
        }
      }
    },
    taskTypeId(id) {
      if (id) {
        this.getTaskFields(this.type);
        this.fetchFromUser(this.taskTypeId);
      }
    },
    'flowSetting.questionId'(){
        this.changeQuestion(this.flowSetting.questionId)
        this.iframeUrl = "/pcoperation/task/evaluate?id="+this.flowSetting.questionId+"&isReviewed=0&isEvaluated=0&isShowPhone=true"
        // document.getElementById('iframepage').src = this.iframeUrl;
    },
    /**点击自定义节点 */
    currentNode(val) {
      this.baseSetActiveTab = 'base';
      
      if(val && val?.type !== 'create') {
        this.getTaskFields(this.type);
      }
    }
  },
  methods: {
    /** 选择节点负责人 */
    handleChooseUserSubmit(value) {
      this.$set(this.flowSetting, 'nodeResponsiblePerson', value);
    },
    /**获取支付配置 */
    async getOnlineAlipaySetReq() {
      try {
        let res = await PayApiApi.getOnlineAlipay();
        const {success, data} = res;
        if(success) {
          this.isOnlineAlipay = data?.sysSwitch ? true : false;
        }
      } catch (error) {
        console.error('fetch getOnlineAlipaySetReq => error', error);
      }
    },
    /** 触发支付设置 */
    async onChangeOnlinePay(event) { 
      try {
        if(!this.flowSetting.finishOnlinePay) return;

        await this.getOnlineAlipaySetReq();
        
        if (!this.isOnlineAlipay) {
          const h = this.$createElement;
          this.$set(this.flowSetting, 'finishOnlinePay', false);

          const messageContent = [
            this.$t('task.paySet.tip2'),
            h('span', {
              on: {
                click: this.handleGoToPaymentSetting
              }
            }, this.$t('common.base.toSet'))
          ];

          return this.showWarningMessage(messageContent);
        }
      } catch (error) {
        console.error(error);
      }
    },
    /**打开支付设置 */
    handleGoToPaymentSetting() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePaymentSetting,
        reload: true,
      });
    },

    showWarningMessage(content) {
      const h = this.$createElement;
      this.$message({
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: h('div', { class: 'warning' }, content)
      });
    },
    reset(){
      this.showGuideDialog = false;
    },
    toSetMessage(){      
      let fromId = window.frameElement.getAttribute('id');

      if(rootWindowInitData.openMessageReform){
        openAccurateTab({
          type: PageRoutesTypeEnum.PageSettingMessage,
          params:'appId=orderMessage'	
        })
        return
      }

      openAccurateTab({
        type: PageRoutesTypeEnum.PageSettingSmsmessage,
        reload: true,
        fromId
      })
    },
    copyText() {
      setClipboardData(
        this.guideMessage.COPY_TEXT_MESSAGE,
        () => {
          Platform.notification({
            message: this.guideMessage.COPY_TEXT_SUCCESS,
            type: 'success',
          });
        },
        () => {
          Platform.notification({
            message: this.guideMessage.COPY_TEXT_FAIL,
            type: 'warning',
          });
        }
      );  
    },
    buildApproveOptions() {
      this.options.flow = this.approveOptions(this.type);
      this.options.pause = this.approveOptions('pause');
      this.options.cancel = this.approveOptions('cancel');
    },
    /** 审批类型选项 */
    approveOptions(type) {
      let options = [
        {
          value: 'leader',
          label: this.$t('common.task.approversList[0]'),
        },
        {
          value: 'users',
          label: this.$t('common.task.approversList[1]'),
        },
        {
          value: 'createUser',
          label: this.$t('common.task.approversList[2]'),
        },
        {
          value: 'userAdmin',
          label: this.$t('common.task.approversList[3]'),
        },
        // {
        //   value: 'sendUser',
        //   label: this.$t('event.setting.serviceEventTypeSetting.flow.component.settingFlowSpecific.label7'),
        // },
        {
          value: 'promoter',
          label: this.$t('common.task.approversList[4]'),
        },
      ];

      options = [
        ...options,
        ...this.formList.map((item) => {
          return {
            label: `${this.$t('task.setting.taskTypeSetting.flow.components.formUser')}:${ item.showName}`,
            value: item.stateTemplateId,
          };
        }),
      ];

      if (type !== 'create' && type !== 'allot') {
        options.splice(3, 0, {
          value: 'allotUser',
          label: this.$t('task.setting.taskTypeSetting.flow.components.taskDispatcher'),
        });
      }

      if (!['allot', 'accept', 'start', 'pause'].includes(type)) {
        options = [
          ...options,
          ...this.receiptList.map((item) => {
            return {
              label: `${this.$t('task.setting.taskTypeSetting.flow.components.reviewFormUser')}:${ item.showName}`,
              value: item.stateTemplateId,
            };
          }),
        ];
      }

      return options;
    },
    /** 获取工单表单、回执表单中必填的人员字段 */
    async fetchFromUser(id) {
      try {
        let res = await SettingApi.getFromUser(id);
        this.formList = res.data.list;
        this.receiptList = res.data.receiptList;

        this.buildApproveOptions();
        this.compKey = safeNewDate().getTime();
      } catch (error) {
        console.error('fetch getFromUser => error', error);
      }
    },
    /**
     * 获取工单表单/回执表单自定义字段
     */
    async getTaskFields(type) {
      if (['create', 'finish', ...(this.isHaveNodeFlowAuth ? TASK_NODE_MODE : [])].includes(type)) {
        try {
          const params = {
            tableName: this.mode,
            typeId: this.taskTypeId,
            isFromSetting: false,
            isShowRichText:true
          }
          if(this.isHaveNodeFlowAuth && TASK_NODE_MODE.includes(type)){
            params.isCommonNode = Boolean(this.currentNode.isCommon)
          }
          let fields = await TaskApi.getAllFields(params);
          this.fields = fields || [];
        } catch (error) {
          console.error('fetch task getAllFields => err', error);
        }
      }
    },
    async beforeOpenFormRemind(){
      try {
        // 判断当前节点是否还没有保存
        if(this.currentNode?.type == 'normal' && this.isNewNormalNode) {
          await this.$confirm(this.$t('event.setting.serviceEventTypeSetting.flow.tips2'), '', {
            confirmButtonText: this.$t('common.base.save'),
            cancelButtonText: this.$t('common.base.notSaveForNow'),
            type: 'warning',
            closeOnClickModal: false
          })
          this.$eventBus.$emit('task_custom_node_save', true, this.openFormDesign);
        }else {
          this.openFormDesign();
        }
      } catch (e) {
        console.error(e)
      }
    },
    /**
     * 打开表单编辑器
     */
    openFormDesign() {
      this.$refs.taskFormSetting.open();
    },
    changeQuestion(id) {
      this.usedConfigList.find((item)=>{//model就是上面的数据源
        if(item.satisfactionId === id){
          this.questionId = item.id;
        }
      });
      this.baseSetActiveTab = 'base'
    },
    openSetReviewQuestion() {
      // this.$emit('saveSubmit');
      let fromId = window.frameElement.getAttribute('id');

      let questionId = this.questionId;
      openAccurateTab({
        fromId,
        type:questionId ? PageRoutesTypeEnum.PageQuestionnaireSchemeEdit : PageRoutesTypeEnum.PageCustomerExperienceQuestionnaireSchemeList,
        key:questionId ? questionId : ''
      });
    },
    /** 更新审批设置 */
    changeApproveSetting(setting, key) {

      console.log(setting, '改变了')

      switch (key) {
      case 'pause':
        this.$set(this.taskTypeConfig, 'pauseApproveSetting', setting);
        break;
      case 'cancel':
        this.$set(this.taskTypeConfig, 'cancelApproveSetting', setting);
        break;
      case 'assign':
        this.$set(this.flowSetting, 'approveSetting', setting);
        break;
      case 'reassign':
        this.$set(this.flowSetting, 'transferApprove', setting);
        break;
      default:
        break;
      }
    },
    /** 更新流程超时提醒设置 */
    updateOvertimeSetting() {
      let index = this.taskTypeConfig.taskOverTimeModels.findIndex(
        (item) => item.overTimeState === this.type
      );
      if (index > -1) {
        this.$set(
          this.taskTypeConfig.taskOverTimeModels,
          index,
          this.taskOverTimeModel
        );
        return
      }
      if (this.type==='review') {
        this.$set(
          this.taskTypeConfig.taskOverTimeModels,
          this.taskTypeConfig.taskOverTimeModels.length,
          this.taskOverTimeModel
        );
      }
    },
    /** 格式化审批人员名称 */
    getApproverNames(approvers) {
      return approvers.map((item) => item.displayName).join(',');
    },
    /** 选择指定审批人员 */
    selectApproveUser(type) {
      let selected = [];

      if (type === 'overTime') selected = this.taskOverTimeModel.reminders;
      if (type === 'planRemind') selected = this.taskTypeConfig.noticeUsers;

      let options = {
        title: ['overTime', 'planRemind'].includes(type) ? this.$t('task.setting.taskTypeSetting.flow.components.tip3') : this.$t('task.setting.taskTypeSetting.flow.components.tip4'), // [选填] 默认值为 '请选择人员'
        max: 14, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        mode: BaseSelectUserModeEnum.Filter
      };

      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0) return;
          switch (type) {
          case 'overTime': // 超时审批指定人员
            this.taskOverTimeModel.reminders = res.data.users;
            this.updateOvertimeSetting();
            break;
          case 'planRemind': // 计划提醒指定人员
            this.taskTypeConfig.noticeUsers = res.data.users;
            break;
          default:
            break;
          }
        })
        .catch((err) => {
          console.warn(err);
        });
    },
    /** 刷新字段和表单必填人员 */
    refreshFields() {
      this.getTaskFields(this.type);
      this.fetchFromUser(this.taskTypeId);
    },
    async getUsedConfigList() {
      try {
        let res = await SettingApi.getUsedConfigList({});
        this.usedConfigList = res.result || [];
      } catch (error) {
        console.error('fetch getUsedConfigList => err', error);
      }
    },


    async initData() {
      await this.getTypeData('task');
      await this.getTypeData('task_receipt')
      if (this.type === 'finish') {
        await this.getReceiptAmountData()
      }
      await this.setDefaultFiledList()
    },

    setDefaultFiledList() {
      if (this.optionMaps['task'].length > 0 || this.optionMaps['task_receipt'].length >0 ) {
        this.setData(this.flowSetting.approveSetting)
        this.setData(this.flowSetting.transferApprove)
      }
    },
    

    setData(approveSetting) {
      
      if (approveSetting && approveSetting.conditions && approveSetting.conditions.length > 0) {
          this.setDefaultConditions(approveSetting.conditions)
      }
      if (approveSetting && approveSetting.level > 1) {
        // 二级审批存在
        if (approveSetting.multiApproverSetting && approveSetting.multiApproverSetting.length >0 && approveSetting.multiApproverSetting[0].conditions) {
          this.setDefaultConditions(approveSetting.multiApproverSetting[0].conditions)
        }
      }
    },

    setDefaultConditions(conditionsList) {
      conditionsList.forEach((item) => {
          item.forEach((ele)=> {
              this.$set(ele, 'fieldsOptions', this.optionMaps[ele.module]);
              if (ele.conditionItem.valueStr) {
                this.$set(ele.conditionItem, 'value', JSON.parse(ele.conditionItem.valueStr))
              }
              if (ele.conditionItem.fieldName) {
                  this.optionMaps[ele.module].forEach((eleDetail)=> {
                    if (eleDetail.ruleName === ele.conditionItem.ruleName ) {
                        // 如果回执金额存在, ruleName就是唯一匹配值
                        this.$set(ele.conditionItem, 'field', eleDetail);
                        this.$set(ele.conditionItem, 'fieldName', eleDetail.ruleName);
                      // }
                    } else {
                      if (eleDetail.fieldName === ele.conditionItem.fieldName) {
                          this.$set(ele.conditionItem, 'field', eleDetail);
                      }
                    }
                  })
              }
          })
        })
    },

    // 工单/工单回执字段列表接口
    async getTypeData(tableName) {
      let params = {
        tableName: tableName,
        typeId: this.taskTypeId,
        isFromSetting: true,
        isShowRichText: false,
      }
      let allShowList = []
      await TaskApi.getAllFields(params).then(res=>{
        if (res) {
          res.forEach((item)=> {
            if (this.filterTypeList.includes(item.formType)) {
              allShowList.push(item)
            }
          })

          this.optionMaps[tableName] = allShowList;
        }
      })

    },

    // 回执金额规则接口
    async getReceiptAmountData() {
      let params = {
        moduleId: this.taskTypeId,
      }
      await TaskApi.getSettlementRule(params).then((res) => {
        if (res.result) {
          res.result.forEach((item) => {
            item.formType = 'number'
            item.operator = ''
            item.displayName = item.ruleName
            // 唯一值
            item.fieldName = item.ruleName
            item.business = item.business
          })
          this.optionMaps['task_receipt_amount'] = res.result

        }
      })
    },
  },
  mounted() {
    this.$eventBus.$on('setting_task_type_name', (taskTypeName) => {
      this.taskTypeName = taskTypeName;
    });
    this.getUsedConfigList();
    // this.initData()
    console.log('flowSetting',this.flowSetting, '最外面的数据1212')
  },
  beforeDestroy() {
    this.$eventBus.$off('setting_task_type_name');
  },
  components: {
    [ApproveSetting.name]: ApproveSetting,
    [TaskFieldsSetting.name]: TaskFieldsSetting,
    [TriggerListSetting.name]: TriggerListSetting,
    [CardListSetting.name]: CardListSetting,
    [ProcessNodeSetting.name]: ProcessNodeSetting,
  },
};
</script>

<style lang="scss">
.task-flow-setting {
  display: flex;
  .flow-setting-left {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #ffffff;
    margin-right: 12px;
    border-radius: 0 0 4px 4px;
    line-height: 38px;
    &.flex-direction-column {
      flex-direction: column;
    }
    .flow-setting-form-preview {
      padding-top: 20px;
    }
    .form-preview-box{
      position: absolute;
      bottom: 40px;
      left: 16px;
      z-index: 9;
      text-align: center;
      width: calc(100% - 32px);
      height: 50px;
      line-height: 50px;
      background: #ffffff;
      .form-preview-btn {
        width: calc(100% - 20px);
      }
    }
    .flow-preview-guide {
      position: absolute;
      top: 25%;
      z-index: 9;
      text-align: center;
      width: 100%;
      img {
        width: 128px;
      }
      .form-no-tip {
        width: 300px;
        font-size: 12px;
        margin: auto;
        color: $text-color-secondary;

      }
    }
    .guide-tip {
      position: absolute;
      width: 300px;
      font-size: 12px;
      color: $color-primary;
      bottom: 90px;
      text-align: center;
      p {
        margin-bottom: 0px;
        line-height: 20px;
      }
      .iconfont {
        display: block;
        font-size: 20px;
      }
    }
  }
  .flow-setting-right {
    min-width: 430px;
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    .setting-specific {
      height: 100%;
      font-size: 14px;
      padding: 8px 20px 20px 20px;
      background: #ffffff;
      color: #999999;
      border-radius: 0 0 4px 4px;
      h2 {
        color: #333333;
        font-size: 14px;
        margin: 20px 0 8px 0;
      }
      p {
        line-height: 38px;
        margin-bottom: 0;
      }
      &-form {
        p {
          cursor: pointer;
          color: #666666;
          &:hover {
            color: $color-primary;
          }
        }
      }
      .set-review-question{
        min-width: 110px;
        color: $color-primary-light-6;
        line-height: normal;
        cursor: pointer;
      }
    }

    .setting-common {
      flex: 1;
      margin-top: 12px;
      font-size: 14px;
      background: #ffffff;
      padding: 8px 20px 20px 20px;
      border-radius: 4px;
      color: #999999;
      h2 {
        color: #333333;
        font-size: 14px;
        margin: 20px 0 8px 0;
      }
    }
  }
  .task-review-list-dialog-body{
    padding: 20px;
    .task-review-list-dialog-body-text{
      margin-bottom: 20px;
      span{
        float:right;
        color:#00aeff;
      }
    }
    .task-review-list-dialog-body-text-min{
      color: #f00;
      font-size: 10px;
    }
    .task-review-list-dialog-body-btn-group{
      text-align: right;
    }
  }
}

.form-design-main .form-design-center{
  height: 90%;
}

.w-87 {
  width: 87px;
}

.w-187 {
  width: 187px;
}

.ml-12 {
  margin-left: 12px;
}

.mt-8 {
  margin-top: 8px;
}

.mt-12{
  margin-top: 12px !important;
}

.mb-8 {
  margin-bottom: 8px;
}

.lh-38{
  line-height: 38px;
}

/** element style */
::v-deep .el-input{
  line-height: 38px;
}
::v-deep .el-checkbox{
  margin-bottom: 0;
}
.warning {
  color: #E6A23C;
  width:80%;
  display: flex;
  justify-content: space-between;
  span {
    text-align: right;
    color: $color-primary;
    cursor: pointer;
  }
}

</style>

<style lang="scss">
.setting-specific-overtime {
  .ui-input-block {
    display: inline-block;
    width: 200px;
    margin-right: 5px;
    .open-data {
      margin-right: 0;
    }
  }
  & > div {
    display: flex;
    align-items: center;
    flex-flow: wrap;
    .el-select {
      margin: 0 5px;
    }
  }
}
.task-form-preview-container {
  .form-design-preview-disabled:last-child {
    margin-bottom: 45px;
  }
}
</style>